﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ModelRelationship
{
    /// <summary>
    /// 一对一实体关系配置
    /// </summary>
    public class OneToOneRelationshipDbContext : DbContext
    {
        public DbSet<User> Users => Set<User>();
        public DbSet<UserInfo> UserInfos => Set<UserInfo>();

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<User>(b =>
            {
                b.HasOne(u => u.UserInfo)
                .WithOne(ui => ui.User)
                .HasForeignKey<UserInfo>(ui => ui.UserId);
            });

            modelBuilder.Entity<UserInfo>(b =>
            {
                b.HasOne(ui => ui.User)
                .WithOne(u => u.UserInfo)
                .HasForeignKey<UserInfo>(ui => ui.UserId);
            });

        }

    }


    public class User
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Password { get; set; }

        [ForeignKey("UseId")]
        [InverseProperty("User")]
        public UserInfo UserInfo { get; set; }
    }

    public class UserInfo
    {
        public int Id { get; set; }
        public string NickName { get; set; }
        public string PersonalTag { get; set; }

        [ForeignKey("User")] //①③
        public int? UserId { get; set; }
        [ForeignKey("UserId")] //①③
        [InverseProperty("UserInfo")] //②③
        public User User { get; set; }
    }
}
